﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using UnityEngine.EventSystems;
public class ViewUI :MonoBehaviour {
	string m_PathItem = "";
	public ListItemManage m_List = new ListItemManage();
	public delegate void CallBack();
	public event CallBack _onClose;
	public int nowDepth;
	public void SetBtn(bool boolean,UISprite uispe,string truename,string falsename){
		if (boolean)
			uispe.spriteName = truename;
		else
			uispe.spriteName = falsename;
	}
	protected string GetPathItem(string fname){
		return ObjManager.Instance.PathUIPanel+fname+"/Item/";
	}
	protected string PathItem{
		get{
			if(m_PathItem == null || m_PathItem == "")
				m_PathItem = ObjManager.Instance.PathUIPanel+ BaseModel.Instance.ModueName +"/Item/";
			return m_PathItem;
		}
	}
	public bool UseNGUI{
		get{ return true;}
	}
	public MyOBJ _myObjs;
	public MyOBJ c_MyObjs{
		get{
			if (_myObjs == null)
				_myObjs = GetComponent<MyOBJ> ();
			return _myObjs;
		}
		set{ 
			_myObjs = value;
		}
	}
	public virtual void Init(){
		c_MyObjs = gameObject.GetComponent<MyOBJ>();
	}
	protected virtual void UpdateState(float dt){
		
	}
	void Start(){
		StartCoroutine(CoWaitForAframe ());
		AfterStart ();
	}
	protected virtual void AfterStart(){
		
	}
	IEnumerator CoWaitForAframe(){
		yield return null;
		WaitForAframe();
	}
	/// <summary>
	/// Open 之后延迟一帧
	/// </summary>
	protected virtual void WaitForAframe(){
		
	}
	/// <summary>
	/// 自动设置panel层级
	/// </summary>
	protected void SetUIGridDepth(){
		try{
			UIPanel panel;
			Transform grid;
			grid = GetObj().GetTransform("UIGrid");
			panel = grid.parent.GetComponent<UIPanel>();
			panel.depth = GetPanelDepth ()+1;
		}
		catch{
		}
	}
	public int GetPanelDepth(){
		string name;
		name = transform.parent.name;
		switch (name) {
		case "PanelBG":return 1;
		case "PanelDown":return 3;
		case "PanelMiddle":return 5;
		case "PanelUp":return 7;
		case "PanelTop":return 9;
		}
		return 0;
	}
	/// <summary>
	/// 将RectTransform平铺展开 所有数值归零
	/// </summary>
	public void RectTransform_RestZero(){
		RectTransform rt;
		rt = gameObject.GetComponent<RectTransform>();
		rt.sizeDelta =new Vector2 (0,0);
	}
	public MyOBJ GetObj(){
		return c_MyObjs;
	}
	public UISprite GetUISprite(string name){
		UISprite uispr;
		uispr =GetObj(name).GetComponent<UISprite> ();
		if(uispr == null)
			uispr = GetObj(name).GetComponentInChildren<UISprite> ();
		return uispr;
	}
	GameObject GetObj(string name){
		if(c_MyObjs)
			return c_MyObjs.GetObj(name);
		else
			return null;
	}
	public bool GetToggle(string name){
		return GetObj ().GetGameObject (name).GetComponent<UIToggle> ().value;
	}
	public void SetToggle(string name,bool value){
		try{
			GetObj ().GetGameObject (name).GetComponent<UIToggle>().value = value;
		}
		catch{
			Debug.Log("NoFindToggle  " +name);
		}
	}
	public void SetActive(string name,bool active){
		try{
			GetObj ().GetGameObject (name).SetActive (active);
		}
		catch{
			Debug.LogWarning("UnFind"+name);
		}
	}
	protected virtual void DisListener(){
		
	}
	protected virtual void InitListener(){
		
	}
	public virtual void Open(){
		InitListener ();
	}
	protected virtual void OnClose<Type>(){
		DisListener ();
		if (_onClose != null)
			_onClose ();
		_onClose = null;
		ViewUIMgr.Instance.Close<Type>(this);
	}
	public virtual void Close(){
		
	}
	/// <summary>
	/// 刷新UI
	/// </summary>
	public virtual void RefreshUI(){

	}
	public virtual void Hide(){
		gameObject.SetActive (false);
	}
	public virtual void Show(){
		gameObject.SetActive (true);
	}
	public EventTrigger GetEventTrigger(string name){
		EventTrigger et;
		et =  c_MyObjs.GetGameObject(name).GetComponent<EventTrigger>();
		return et;
	}
	public void AddToogle(string name,EventDelegate.Callback callback){
		UIToggle button;
		button = c_MyObjs.GetGameObject(name).GetComponent<UIToggle>();
		if (button) {
			button.onChange.Add(new EventDelegate(callback));
		}
	}
	public void AddButtonListener (string name,UIEventListener.VoidDelegate callback){
		GameObject target = c_MyObjs.GetGameObject (name);
		if (target != null) {
			NGUITools.AddWidgetCollider (target);
			UIEventListener.Get(target).onClick = callback;
		}
	}	
	public void AddButtonListenerOnPress (string name,UIEventListener.BoolDelegate callback){
		GameObject target = c_MyObjs.GetGameObject (name);
		if (target != null) {
			NGUITools.AddWidgetCollider (target);
			UIEventListener.Get(target).onPress = callback;
		}
	}
	public void AddButton(string name,EventDelegate.Callback callback){
		UIButton button;
		button = c_MyObjs.GetGameObject(name).GetComponent<UIButton>();
		if (button) {
			button.onClick.Add(new EventDelegate(callback));
		}
	}
	public Button GetButton(string name){
		Button button;
		button = c_MyObjs.GetGameObject(name).GetComponent<Button>();
		if (button != null)
		{         
			button.onClick.RemoveAllListeners();
		}
		return button;
	}
	protected UISlider GetUISlider(string name){
		UISlider slider = null;
		GameObject obj = GetObj (name);
		if (obj == null) {
			Debug.Log (gameObject.name + " un find Obj " + name + "in myobj");
		} else {
			slider = GetObj (name).GetComponent<UISlider> ();
		}
		return slider;
	}
	protected UILabel GetUILabel(string name){
		UILabel uilabel = null;
		GameObject obj = GetObj (name);
		if (obj == null) {
			Debug.Log (gameObject.name + " un find Obj " + name + "in myobj");
		} else {
			uilabel = GetObj (name).GetComponent<UILabel> ();
		}
		return uilabel;
	}
	public void SetUILabel(string name,string value){
		UILabel uilabel;
		uilabel = GetObj (name).GetComponent<UILabel> ();
		if (uilabel != null)
			uilabel.text = value;
		else
			Debug.Log("In" + name+ " >>FindUILabel>> IsNull"); 
	}
	public void SetButtonSize(string name,Vector3 value){
		BoxCollider button;
		button = GetObj().GetGameObject(name).GetComponent<BoxCollider>();
		button.size = value;
	}
	public void SetNGUIItemPos(){
		StartCoroutine (SetItemAction ());
	}
	IEnumerator SetItemAction(){
		m_List.SetItemActive (false);
		yield return null;
		m_List.SetItemActive (true);
		m_List.RestPos ();
	}
	protected void ShowSprite(string name){
		SpriteColor (name, 1);
	}
	protected void HideSprite(string name){
		SpriteColor (name, 0);
	}
	protected void SpriteColor(string name,int value){
		UIWidget widget;
		widget = GetObj ().GetGameObject (name).GetComponent<UIWidget> ();
		if (widget == null) {
			Debug.Log("NoFind Widget"+name);
			return;
		}
		Color c = new Color();
		c = widget.color;
		c.r = value;
		widget.color = c;
	}
    public void SetAnchor()
    {
        UIWidget widget = GetComponent<UIWidget>();
		if(widget!=null)
        widget.SetAnchor(transform.parent.parent.parent);
    }
	public virtual void UpdateAnchor(){
		SetAnchor ();
	}
}


public class ListItemManage{
	GridLayoutGroup Grid;
	UIGrid m_NGUIGrid;
	Transform m_GridTransform;
	Transform ItemPrefab;
	//		Function OnClickCB:;
	//		delegate OnClickCB;
	
	public ListItem.UIListItemCallBack OnClick;
	List<MyOBJ> ShowItemS = new List<MyOBJ>();
	List<MyOBJ> HideItemS = new List<MyOBJ>();
	string ListType;
	int getindex = 0;
	bool m_UseNGUI;
	void AddItem(){
		
	}
	public void Add(ListItem item){
		ShowItemS.Add (item.MyObj);
		getindex++;
	}
	public ListItem GetItem(int id){
		if(ShowItemS [id]!=null)
			return ShowItemS [id].GetComponent<ListItem> ();
		else
		return null;
	}
	public int GetCount(){
		return getindex;
	}
	public void Init(MyOBJ hub,string hubname,ListItem.UIListItemCallBack cb,bool UseNGUI){
		m_UseNGUI = UseNGUI;
		if (!UseNGUI) {
			Grid = hub.GetGameObject (hubname).GetComponent<GridLayoutGroup> ();
			m_GridTransform= Grid.transform;
		} else {
			m_NGUIGrid= hub.GetGameObject (hubname).GetComponent<UIGrid> ();
			m_GridTransform= m_NGUIGrid.transform;
		}

		ListType = hubname;
		ItemPrefab = m_GridTransform.parent.Find("Item");
		OnClick = cb;
		if (ItemPrefab == null) {
			Debug.Log ("IP == nu");
			return;
		}
		if (m_GridTransform == null)
			Debug.Log ("m_GridTransform == nu");
		ObjManager.SetParentAndRest(ItemPrefab,m_GridTransform);
		ShowItemS.Add(ItemPrefab.GetComponent<MyOBJ>());
	}
	public void SetItemPrefab(Transform target){
		MyOBJ obj = target.GetComponent<MyOBJ> ();
		if (obj != null) {
			ObjManager.SetParentAndRest(target, m_GridTransform);
			ShowItemS.Add (obj);
		}
	}
	public void GC(int count,bool refreshparent = false){
		int nowcount;
		nowcount = ShowItemS.Count;
		for(var i = count;i < nowcount;i++){
			Destroy(refreshparent);
		}
		getindex = 0;
	}
	public void Destroy(bool refreshparent){
		int count;
		count = ShowItemS.Count - 1;
		HideItemS.Add(ShowItemS[count]);
		if (!m_UseNGUI) {
			ShowItemS [count].GetComponent<LayoutElement> ().ignoreLayout = true;
		}
		if(refreshparent)
			ShowItemS [count].transform.SetParent (ShowItemS [count].transform.parent.parent);
		ShowItemS[count].gameObject.SetActive(false);
		ShowItemS.RemoveAt(count);
	}
	public ListItem Add(){	
		MyOBJ hub;
		if(ShowItemS.Count > getindex)
			hub = ShowItemS[getindex];
		else if(HideItemS != null && HideItemS.Count > 0){
			hub = HideItemS[HideItemS.Count - 1];
			if (!m_UseNGUI) {
				hub.GetComponent<LayoutElement>().ignoreLayout = false;
			}
			hub.gameObject.SetActive(true);
			ShowItemS.Add(hub);
			HideItemS.RemoveAt(HideItemS.Count - 1);
		}
		else
			hub = AddNew();
		ListItem li;
		li = ListItem.Init(hub.gameObject,ListType,getindex,OnClick);
		getindex++;
		return li;
	}
	public void RestPos(){
		if (m_UseNGUI) {
			m_NGUIGrid.repositionNow = true;
			m_NGUIGrid.Reposition();
		}
	}
	public void SetItemActive(bool active){
		for (int i =0; i < ShowItemS.Count; i++) {
			ShowItemS[i].gameObject.SetActive(active);
		}
	}
	MyOBJ AddNew(){
		GameObject obj;
		
		MyOBJ hub;
		obj = ObjManager.Instance.AddChild(ItemPrefab.gameObject,m_GridTransform);
		obj.transform.localScale = Vector3.one;
		obj.SetActive(true);
		
		hub = obj.GetComponent<MyOBJ>();
		ShowItemS.Add(hub);
		return hub;
	}

}

